package com.weetop.akly.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.View;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.weetop.akly.activity.login.LoginActivity;
import com.weetop.akly.apiUtils.ApiRetrofit;
import com.weetop.akly.apiUtils.ApiServer;
import com.weetop.akly.appConfig.MyApplication;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.base.mvp.BaseObserver;
import com.weetop.akly.base.mvp.BasePresenter;
import com.weetop.akly.base.mvp.BaseView;
import com.weetop.akly.bean.PostMessage;
import com.weetop.akly.utils.EventBusUtil;
import com.weetop.akly.utils.MMKVUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;


/**
 * File descripition:   ftagment 基类
 *
 * @author lp
 * @date 2018/6/19
 */

public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseView {
    public View view;
    protected Activity mActivity;
    public Context mContext;
    protected P mPresenter;
    public MyApplication myApplication;
    protected int pageNum=1;
    protected int pageSize=15;
    protected boolean isClear=false;
    protected abstract P createPresenter();
    protected QMUITipDialog tipDialog;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isRegisterEventBus()) {
            EventBusUtil.register(this);
        }
        myApplication = (MyApplication)getActivity().getApplication();
        mContext = getActivity();
        mPresenter = createPresenter();
        mActivity=getActivity();
    }


    protected ApiServer apiServer = ApiRetrofit.getInstance().getApiService();
    private CompositeDisposable compositeDisposable;

    public void addDisposable(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer));
    }

    @Override
    public void showError(String msg) {

    }


    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return true;
    }


    @Override
    public void onErrorCode(BaseModel model) {
        if (model != null){
            if (model.getCode()==-888){
                final AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(mActivity);
                normalDialog.setTitle("提示");
                normalDialog.setMessage("账号已在其他地方登陆");
                normalDialog.setPositiveButton("重新登陆",(dialog, which) -> {
                    dialog.dismiss();
                });
                normalDialog.setOnDismissListener(dialog -> {
                    MMKVUtils.removeUserToken();
                    MMKVUtils.removeRyToken();
                    RongIM.getInstance().logout();
                    RongUserInfoManager.getInstance().uninit();
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivity(intent);
                    ActivityUtils.finishAllActivitiesExceptNewest();
                    mActivity.finish();
                });
                normalDialog.show();
            }else {
                ToastUtils.showShort(model.getMsg());
            }
        }
    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        this.view = null;
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }


    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(PostMessage event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(PostMessage event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(PostMessage event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(PostMessage event) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }
}
